package com.css.security.core.filter;

import com.css.common.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import springfox.documentation.service.OAuth;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * LogSessionFilter
 *
 * @author hanyx
 * @date 2019/06/13
 */
@Slf4j
@Component
public class LogSessionFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (SecurityUtil.getAuthentication() != null) {
            SecurityUtil.getUser();
            String sessionId = "";
            if (SecurityUtil.getAuthentication().getDetails() instanceof WebAuthenticationDetails) {
                sessionId = ((WebAuthenticationDetails) SecurityUtil.getAuthentication().getDetails()).getSessionId();
            }
            if (SecurityUtil.getAuthentication().getDetails() instanceof OAuth2AuthenticationDetails) {
                sessionId = ((OAuth2AuthenticationDetails) SecurityUtil.getAuthentication().getDetails()).getSessionId();
                if (StringUtils.isBlank(sessionId)) {
                    sessionId = ((OAuth2AuthenticationDetails) SecurityUtil.getAuthentication().getDetails()).getTokenValue();
                }
            }
            MDC.put("reqId", sessionId);
            log.debug("将所有request请求都携带上httpSession {}", sessionId);
        }
        filterChain.doFilter(request, response);
    }
}
